#include <rtthread.h>
#include "board.h"
#include <rtdevice.h>
#include <math.h>

#define ADC_DEV_NAME        "adc0"      /* ADC 设备名称 */
#define ADC_DEV_CHANNEL     7           /* ADC 通道 */
#define REFER_VOLTAGE       330         /* 参考电压 3.3V,数据精度乘以100保留2位小数*/
#define CONVERT_BITS        (1 << 10)   /* 转换位数为12位 */


static int mq135(int argc, char *argv[])
{
    rt_adc_device_t adc_dev;
    rt_uint32_t value, vol, ppm;
    rt_err_t ret = RT_EOK;

    uint8_t pin = rt_pin_get("PE.1");
    rt_pin_mode(pin, PIN_MODE_OUTPUT);


    /* 查找设备 */
    adc_dev = (rt_adc_device_t)rt_device_find(ADC_DEV_NAME);
    if (adc_dev == RT_NULL)
    {
        rt_kprintf("mq135 run failed! can't find %s device!\n", ADC_DEV_NAME);
        return RT_ERROR;
    }

    /* 使能设备 */
    ret = rt_adc_enable(adc_dev, ADC_DEV_CHANNEL);
    for(rt_uint8_t i = 0 ; i < 10 ; i++ )
    {
        /* 读取采样值 */
        value = rt_adc_read(adc_dev, ADC_DEV_CHANNEL);
        rt_kprintf("adc value = %d \n", value);

        /* 转换为对应电压值 */
        vol = value * REFER_VOLTAGE / CONVERT_BITS;
        rt_kprintf("voltage = %d.%02d \n", vol / 100, vol % 100);

        ppm = pow((3.4880*0.1*vol)/(5-vol/100),(1.0/0.3203))*100;
        rt_kprintf("ppm = %d.%02d \n", ppm / 100, ppm % 100);
        if(ppm >= 200)
        {
            rt_kprintf("status : danger!\n\n\n");
            rt_pin_write(pin, PIN_LOW);

        }
        else {
            rt_kprintf("status : safe!\n\n\n");
            rt_pin_write(pin, PIN_HIGH);
        }
        rt_thread_mdelay(3000);
    }
    /* 关闭通道 */
    ret = rt_adc_disable(adc_dev, ADC_DEV_CHANNEL);
    rt_pin_write(pin, PIN_HIGH);
    rt_kprintf("exit!\n");
    return ret;
}



int main(void)
{
    rt_kprintf("all initial success!\n");
    uint8_t pin = rt_pin_get("PE.1");
    rt_pin_mode(pin, PIN_MODE_OUTPUT);
    rt_pin_write(pin, PIN_HIGH);
}

/* 导出到 msh 命令列表中 */
MSH_CMD_EXPORT(mq135, air quality monitoring);
